var aj = angular.module('topicViewModule', []);

function CommentController($scope, $http) {
	var actionUrl = '${ctx}/content/comment/' + '${topic.topicId}';
	var start = 0;
	var offset = 3;

	load = function(startParam, offsetParam) {
		$http({
			url : actionUrl,
			method : "GET",
			params : {
				start : startParam,
				offset : offsetParam
			}
		}).success(function(data) {
			if (data.list.length > 0) {
				if (start == 0) {
					$scope.comments = data.list;
				} else {
					jQuery.merge($scope.comments, data.list);
				}
			}

			if (angular.isUndefined($scope.comments)) {
				$scope.commentsRemain = '还未有评论';
			} else {
				var commentsRemain = data.count - $scope.comments.length;
				if (commentsRemain > 0) {
					$scope.commentsRemain = '还有' + commentsRemain + '条回复';
				} else {
					$scope.commentsRemain = '加载结束';
				}
			}

		});
	};

	load(start, offset);

	push = function() {
		var comment = {};
		comment.text = $scope.commentForm.text;
		var userBase = {};
		userBase.userId = '${currentUser.userId}';
		userBase.username = '${currentUser.username}';
		userBase.thumbnailId = '${currentUser.thumbnailId}';
		comment.userBase = userBase;
		if (angular.isUndefined($scope.comments)) {
			$scope.comments = [];
		}
		$scope.comments.push(comment);
	};

	$scope.save = function() {
		if ($scope.commentFormElm.$valid) {
			$http.post(actionUrl, $scope.commentForm).success(function() {
				push();
				$scope.commentForm.text = '';
			});
		}
	};

	$scope.loadMore = function() {
		start += offset;
		load(start, offset);
	};
};